package com.itic.appbase.applications.files.service;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.applications.files.persistence.dao.FilesDao;
import com.itic.appbase.applications.files.persistence.model.Files;
import com.itic.appbase.applications.files.persistence.model.FilesExample;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.StringHelper;


@Service
@Transactional
public class FilesService
     extends CrudService<FilesDao,Files,FilesExample> {
    @Autowired
    private FilesDao filesDao;

    public List<Files> getFiles(String ids){
      String[] arrayIds = ids.split(",");
      FilesExample example = new FilesExample();
      example.createCriteria().andIdIn(Arrays.asList(arrayIds)).andIsEffectiveEqualTo(DBConst.TRUE);
      return filesDao.selectByExample(example);
    }
    
    /**
     * 删除文件记录和文件
     * @param id
     * @return
     */
    public String delFile(String id){
        int code = 0;
        Files files = filesDao.selectByPrimaryKey(id);
        String filePath = files.getFilePath();
        code = filesDao.deleteByPrimaryKey(id);
        if (1 == code){
            File file = new File(FileHelper.getRootDir() + filePath);
            if (file.exists()){
                file.delete();
            }
            return SUCCESS;
        }
        return FAILED;
    }
    
    /**
     * 删除多文件记录和文件
     * @param id
     * @return
     */
    public String delFiles(String ids){
    	String result = FAILED;
    	if( StringHelper.isNotBlank(ids) ){
    		List<String> idList = Arrays.asList(ids.split(","));
    		int i = 0;
    		
    		if( idList.size() > 0 ){
    			for( String temp : idList ){
        			Files files = filesDao.selectByPrimaryKey(temp);
        			String filePath = files.getFilePath();
        			int code = filesDao.deleteByPrimaryKey(temp);
        			if( code == 1 ){
        				i++;
        				File file = new File(FileHelper.getRootDir() + filePath);
        	            if (file.exists()){
        	                file.delete();
        	            }
        			}
        		}
    		}
    		
    		if( idList.size() == i ){
    			result = SUCCESS;
    		}
    	}
    	return result;
    }
}